package com.sky.service.impl;

import com.sky.mapper.CommonMapper;
import com.sky.service.CommonService;
import org.apache.tomcat.jni.FileInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
public class CommonServiceImpl implements CommonService {
    @Value("${file.upload-dir}")
    private String uploadDir;
    @Autowired
    private CommonMapper commonMapper;
    String path;
    @Override
    public String upload(MultipartFile file) {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 生成唯一文件名（避免覆盖）
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uniqueFileName = UUID.randomUUID() + fileExtension;

        // 创建存储目录（如果不存在）
        File targetDir = new File(uploadDir);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }

        // 保存文件到本地
        try {
            Path filePath = Paths.get(uploadDir, uniqueFileName);
            path = filePath.toFile().getAbsolutePath();
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        }catch (IOException e) {
            e.printStackTrace();
        }

        // 返回文件访问路径（例如：http://localhost:8080/files/xxx.jpg）
        return "/files/" + uniqueFileName;
    }
}
